package com.quanyan.user.service.impl;

/**
 * Created by slong.guo on 2017/2/10.
 */

import com.quanyan.api.APIResponse;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.common.Plugin.Page;
import com.quanyan.user.mapper.TbTaskEggConfMapper;
import com.quanyan.user.mapper.TbTaskEggUserMapper;
import com.quanyan.user.model.db.TbTaskEggConf;
import com.quanyan.user.model.db.TbTaskEggConfExample;
import com.quanyan.user.model.db.TbTaskEggUser;
import com.quanyan.user.model.db.TbTaskEggUserExample;
import com.quanyan.user.model.vo.response.RespDoEggTask;
import com.quanyan.user.model.vo.response.RespTaskEggInfo;
import com.quanyan.user.model.vo.response.RespTaskEggItem;
import com.quanyan.user.service.TaskEggService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class TaskEggServiceImpl implements TaskEggService {

    private static final Logger logger = LoggerFactory.getLogger(TaskEggServiceImpl.class);

    @Autowired
    private TbTaskEggConfMapper tbTaskEggConfMapper;

    @Autowired
    private TbTaskEggUserMapper tbTaskEggUserMapper;

    @Autowired
    private UserAssetsService userAssetsService;

    @Override
    public APIResponse<RespTaskEggInfo> getTaskEggInfo(int uid) {
        List<TbTaskEggConf> eggConfs = getEggConf();
        if (eggConfs == null || eggConfs.isEmpty()) {
            return APIResponse.returnFail("内部配置错误");
        }

        List<TbTaskEggUser> eggUsers = getEggUserInfo(uid);
        List<RespTaskEggItem> eggItems = new ArrayList<>();
        RespTaskEggInfo eggInfo = new RespTaskEggInfo();

        for (TbTaskEggConf eggConf : eggConfs) {
            RespTaskEggItem eggItem = new RespTaskEggItem();
            eggItem.setDay(eggConf.getDay());
            eggItem.setNum(eggConf.getEgg());
            eggItem.setObtained(1);////不再增加鸟蛋了 直接置为已掏
            for (TbTaskEggUser eggUser : eggUsers) {
                ////不再增加鸟蛋了 直接置为已掏
                //if (eggUser.getDay().equals(eggConf.getDay())) {
                    eggItem.setObtained(1);
                    eggItem.setNum(eggUser.getNum());
                //}
            }

            eggItems.add(eggItem);
        }

        eggInfo.setEggItems(eggItems);
        eggInfo.setCurDay(getCurDay(new Date()));

        return APIResponse.returnSuccess(eggInfo);
    }

    @Override
    public APIResponse doEggTask(int uid) {

        return APIResponse.returnFail("今天已领过鸟蛋");////不再增加鸟蛋了

//        List<TbTaskEggConf> eggConfs = getEggConf();
//        if (eggConfs == null || eggConfs.isEmpty()) {
//            return APIResponse.returnFail("内部配置错误");
//        }
//
//        RespDoEggTask eggTask = null;
//        List<TbTaskEggUser> eggUsers = getEggUserInfo(uid);
//        if (eggUsers == null || eggUsers.isEmpty()) {
//            eggTask = addUserTaskEgg(uid, eggConfs.get(0).getDay(), eggConfs.get(0).getEgg());
//            return APIResponse.returnSuccess(eggTask);
//        } else {
//            Date now = new Date();
//            TbTaskEggUser recentRecord = eggUsers.get(eggUsers.size() - 1);
//            if (getDayOfYear(now) == getDayOfYear(recentRecord.getObtainTime())) {
//                return APIResponse.returnFail("今天已领过鸟蛋");
//            }
//
//            int day = recentRecord.getDay();
//            for (int i = 0; i < eggConfs.size(); ++i) {
//                if (eggConfs.get(i).getDay().compareTo(day) == 0) {
//                    if (i == eggConfs.size() - 1) {
//                        return APIResponse.returnFail("内部错误，已加到本周上限");
//                    } else {
//                        eggTask = addUserTaskEgg(uid, eggConfs.get(i + 1).getDay(), eggConfs.get(i + 1).getEgg());
//                        return APIResponse.returnSuccess(eggTask);
//                    }
//                }
//            }
//
//        }
//        return APIResponse.returnFail("内部错误");

    }


    @Override
    public boolean addTaskFromOld(int uid, int addEgg){

        return true; //不再增加鸟蛋了

//        logger.info("addTaskFromOld:uid:{},addEgg:{}", uid, addEgg);
//
//        List<TbTaskEggConf> eggConfs = getEggConf();
//        if (eggConfs == null || eggConfs.isEmpty()) {
//            return false;
//        }
//        List<TbTaskEggUser> eggUsers = getEggUserInfo(uid);
//        if(eggUsers == null || eggUsers.isEmpty()){
//            addUserTaskEgg(uid, eggConfs.get(0).getDay(), addEgg);
//        } else {
//            if(eggUsers.size() < eggConfs.size()){
//                addUserTaskEgg(uid, eggConfs.get(eggUsers.size()).getDay(), addEgg);
//            }
//        }
//        return true;
    }

    private RespDoEggTask addUserTaskEgg(int uid, int day, int eggNum) {

        return new RespDoEggTask(); //不再增加鸟蛋了

//        logger.info("uid:{}, day:{}, eggNum:{} while_adding_user_task_egg", uid, day, eggNum);
//        RespDoEggTask eggTask = new RespDoEggTask();
//        if (uid < 0 || day <= 0 || eggNum <= 0) {
//            return eggTask;
//        }
//
//        TbTaskEggUser eggUser = new TbTaskEggUser();
//        eggUser.setUid(uid);
//        eggUser.setDay(day);
//        eggUser.setNum(eggNum);
//        Date now = new Date();
//        eggUser.setWeekTag(getWeekTag(now));
//        eggUser.setObtainTime(now);
//        eggUser.setIsDelete((byte) 0);
//        eggUser.setCreateTime(now);
//        eggUser.setUpdateTime(now);
//
//        tbTaskEggUserMapper.insertSelective(eggUser);
//
//        ReqUserAccumulateModify modify = new ReqUserAccumulateModify();
//        modify.setUid(uid);
//        modify.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
//        modify.setSystemCode(Constants.USER_CENTER_SYSTEM_CODE);
//        modify.setReceiver("用户中心掏鸟蛋");
//        modify.setPayReceive(AssetsPayReceive.SYSTEM.getName());
//        modify.setBusinessCode(Constants.USER_CENTER_RANDOM_EGGS_CODE);
//        modify.setInfo("掏鸟蛋任务");
//        modify.setAccumulate((long) eggNum);
//
//        APIRequest<ReqUserAccumulateModify> apiRequest = new APIRequest<>();
//        apiRequest.setData(modify);
//
//        logger.info("task_egg_add_request_data:{}", modify);
//
//        APIResponse<RespUserAccumulateModify> response = userAssetsService.modifyAccumulate(apiRequest);
//        if (response == null || !response.isRet()) {
//            return eggTask;
//        }
//
//        logger.info("task_egg_record_succeeded:{}", response.getData());
//
//        eggTask.setOpResult(1);
//        eggTask.setAddedNum(eggNum);
//        eggTask.setNowTotal(response.getData().getAccumulate());
//        return eggTask;
    }


    @Override
    public int hasObtainedEgg(int uid, Date date){
        return 1;//不再增加鸟蛋了
//        List<TbTaskEggConf> eggConfs = getEggConf();
//        if (eggConfs == null || eggConfs.isEmpty()) {
//            logger.error("error_in_config_task_egg. req: uid:{} data:{}", uid, date);
//            return 1;
//        }
//
//        List<TbTaskEggUser> eggUsers = getEggUserInfo(uid);
//        if(eggUsers.isEmpty()){
//            return 0;
//        }
//        if(eggConfs.size() <= eggUsers.size()){
//            return 1;
//        }
//
//        Date latest_date = eggUsers.get(eggUsers.size() - 1).getCreateTime();
//
//        return getDayOfYear(date) == getDayOfYear(latest_date) ? 1 : 0;
    }

    private List<TbTaskEggUser> getEggUserInfo(int uid) {
        int weekTag = getWeekTag(new Date());

        TbTaskEggUserExample example = new TbTaskEggUserExample();
        TbTaskEggUserExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andWeekTagEqualTo(weekTag);
        example.setOrderByClause("update_time asc");
        return tbTaskEggUserMapper.selectByExample(example);
    }

    private List<TbTaskEggConf> getEggConf() {
        TbTaskEggConfExample example = new TbTaskEggConfExample();
        TbTaskEggConfExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo((byte) 0);
        example.setPage(new Page(0, 100));
        return tbTaskEggConfMapper.selectByExample(example);
    }

    private int getDayOfYear(Date dt) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(dt);
        return ca.get(Calendar.DAY_OF_YEAR);
    }

    private int getWeekTag(Date dt) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(dt);
        int year = ca.get(Calendar.YEAR);
        int week = ca.get(Calendar.WEEK_OF_YEAR);
        int day = ca.get(Calendar.DAY_OF_WEEK);
        week = day == 1 ? week - 1 : week;
        week = week <= 0 ? 1 : week;
        return year * 100 + week;
    }

    private int getCurDay(Date dt){
        Calendar ca = Calendar.getInstance();
        ca.setTime(dt);
        int curDay = ca.get(Calendar.DAY_OF_WEEK);
        return curDay == 1 ? 7 : curDay - 1;
    }

}
